import { getLocale, setLocale } from 'umi';
//获取本地英文信息
import { enLocaleData, zhLocaleData } from '@/utils/requireUtil';
import { replaceTemplateText } from './replace-text';

const textToUpperCase = function (text: string) {
  let res = text;
  if (_.get(text, 0)) {
    const regex = /^./;
    res = text.replace(regex, text[0].toUpperCase());
  }
  return res;
};

const sentenceToUpperCase = function (text: string) {
  const arr = text.split(' ');
  for (let i = 0; i < arr.length; i++) {
    arr[i] = textToUpperCase(arr[i]);
  }
  return arr.join(' ');
};

function getMessage(id: string, ...params: any) {
  const currentLangulage = window.localStorage.getItem('umi_locale') || 'zh-CN';
  const remoteLangulages = window.remoteLangulages;
  const prdLocales = window.prdLocales;
  let message = id;
  //如果有远程信息，以远程信息为准
  if (remoteLangulages && remoteLangulages[currentLangulage]) {
    _.map(remoteLangulages[currentLangulage], (langulage) => {
      if (langulage.keyword == id) {
        message = langulage.value;
        message = sentenceToUpperCase(message);
      }
    });
  }
  //如果没有远程信息，以本地信息为准
  if (message == id) {
    // 中文直接替换参数
    if (currentLangulage == 'zh-CN') {
      const text = _.get(zhLocaleData, message) || _.get(prdLocales, `[zh-CN].${message}`) || message;
      return sentenceToUpperCase(replaceTemplateText(text, ...params));
    }
    // 英语先获取翻译再替换
    if (currentLangulage == 'en-US') {
      const text = _.get(enLocaleData, message) || _.get(prdLocales, `[en-US].${message}`) || message;
      return sentenceToUpperCase(replaceTemplateText(text, ...params));
    }

    // 未处理语言
    return replaceTemplateText(message, ...params);
  } else {
    return message;
  }
}

const tr = getMessage as any;

window.tr = tr;

export default tr;
export { tr, getLocale, setLocale };
